import socket
from cryptography.fernet import Fernet

# 使用预共享密钥进行加密解密
key = b'pRmgMa8T0INjEAfksaq2aafzoZXEuwKIvDCD8gZW8ek='
cipher = Fernet(key)


def handle_client(conn):
    # 接收数据长度信息
    data_len = int.from_bytes(conn.recv(4), byteorder='big')
    encrypted_data = conn.recv(data_len)

    # 解密数据
    try:
        decrypted_data = cipher.decrypt(encrypted_data)
    except:
        decrypted_data = b"Decryption Error"

    # 写入接收文件
    with open('server_received.txt', 'wb') as f:
        f.write(decrypted_data)
    print(f"已接收并保存 {len(decrypted_data)} 字节数据")

    # 读取回复文件并发送
    try:
        with open('server_response.txt', 'rb') as f:
            response_data = f.read()
        encrypted_resp = cipher.encrypt(response_data)
        conn.send(len(encrypted_resp).to_bytes(4, byteorder='big'))
        conn.sendall(encrypted_resp)
    except FileNotFoundError:
        print("警告：未找到回复文件")


def main():
    host = '0.0.0.0'
    port = 12345

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind((host, port))
        s.listen()
        print("服务端已启动，等待连接...")

        while True:
            conn, addr = s.accept()
            with conn:
                print(f"连接来自: {addr}")
                handle_client(conn)


if __name__ == '__main__':
    main()